package com.demo.jetpack

import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.*

class JetpackApplication: Application(), ViewModelStoreOwner, HasDefaultViewModelProviderFactory {

    private val mViewModelStore by lazy {
        ViewModelStore()
    }

    private val mViewModelFactory by lazy {
        ViewModelProvider.AndroidViewModelFactory.getInstance(this)
    }

    override fun getViewModelStore() = mViewModelStore

    override fun getDefaultViewModelProviderFactory() = mViewModelFactory

    override fun onCreate() {
        super.onCreate()
        // sdk initialization
    }

}

inline fun <reified T: ViewModel> Fragment.appViewModels(
) = object : Lazy<T> {
    override val value: T
        get() = requireActivity().application.viewModels<T>().value
    override fun isInitialized() = true
}

inline fun <reified T: ViewModel> AppCompatActivity.appViewModels(
) = object : Lazy<T> {
    override val value: T
        get() = application.viewModels<T>().value
    override fun isInitialized() = true
}

inline fun <reified T: ViewModel> Application.viewModels(
) = ViewModelLazy(
    T::class,
    { (this as ViewModelStoreOwner).viewModelStore },
    { (this as HasDefaultViewModelProviderFactory).defaultViewModelProviderFactory }
)